const express = require('express');
const User = require('./../models/user');
const { Blog } = require('../models/blog')

const router = express.Router();
const multer = require('multer');  // 文件中间件
const { encryptionData } = require('../utils/tools')

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/uploads');
    },
    filename: function (req, file, cb) {
        const [name, suffix] = file.originalname.split('.');
        cb(null, `${name}_${new Date().getTime()}.${suffix}`);
    }
});
// 权限拦截器
const auth = function (req, res, next) {
    if (req.session.user === undefined) {
        res.redirect('/user/login');
    }
    next();
}

const upload = multer({storage: storage});
// upload.any() 接受一切上传的文件
router.get('/login', function (req, res, next) {
    res.render('login.html');
});

router.post('/login', function (req, res, next) {
    const username = req.body.username;
    const password = req.body.password;
    User.findOne({
        username: username,
        password: encryptionData(password)
    }, function (err, data) {
        if (err) {
            return res.status(500).json({
                err_code: 500,
                msg: '服务器错误'
            })
        }
        if (data === null) {
            return res.status(200).json({
                err_code: -1,
                msg: '用户名或密码错误'
            })
        }
        req.session.user = {
            username: data.username,
            avatar: data.avatar,
            user_id: data._id,
            email: data.email
        };
        return res.status(200).json({
            err_code: 0,
            msg: '登录成功'
        })
    });
});

router.get('/register', function (req, res, next) {  // 注册
    res.render('register.html');
});

router.post('/register', function (req, res, next) {  // 注册
    const { username, password, email } = req.body;
    User.findOne({
        $or: [
            {username},
            {email}
        ]
    }, function (err, data) {
        if (err) {
            return res.status(500).json({
                err_code: 500,
                msg: '服务端错误'
            });
        }
        if (data) {
            // 邮箱或昵称已存在
            return res.status(200).json({err_code: -1, msg: '邮箱或用户名已存在'});
        }
        new User({
            email,
            username,
            password: encryptionData(password)
        }).save(function (err, user) {
            if (err) {
                return res.status(500).json({
                    err_code: 500,
                    msg: '服务端错误'
                });
            }
            // 注册，即登录
            // 注册成功,通过session，记录用户登录状态
            req.session.user = {
                username: user.username,
                avatar: user.avatar,
                user_id: user._id,
                email: user.email
            };
            // 提供了json()方法
            res.status(200).json({err_code: 0, msg: 'ok'});
        });
    })
});

router.get('/logout', function (req, res) {
    req.session.destroy(); // 销毁session
    res.redirect('/user/login'); // 重定向到登录页
});

router.get('/center', auth, async function (req, res, next) { // 个人中心
    const user_session = req.session.user; // 获取登录用户的 session
    try {
        const user = await User.findOne({username: user_session.username}).exec(); // 通过async的方式查询数据
        delete user.password;
        return res.render('user-center.html', {user: user}); // render方法执行后，会接着执行
    } catch (e) {
        console.log(e.toString());
    }
});

// 更新表单
router.post('/center', auth, upload.single('avatar'), async function (req, res, next) {
    const body = req.body;
    const file = req.file;
    try {
        if (file) { // 如果file没有文件，这说明不是更新头像
            body.avatar = `/uploads/${file.filename}`;
            req.session.user.avatar = body.avatar; // 更新session
        }
        const user = req.session.user
        if (body.email !== user.email) {
            const result = await User.find({email: body.email})
            if (result.length > 0) {
                return res.json({
                    err_code: -1,
                    msg: '邮箱已存在'
                })
            }
        }
        // findOneAndUpdate返回的数据是之前的
        await User.findOneAndUpdate({username: user.username}, body).exec();
        return res.status(200).json({
            err_code: 0,
            msg: '用户信息更新成功'
        });
    } catch (e) {
        console.log(e);
        return res.status(500).json({
            err_code: 500,
            msg: '服务器错误'
        });
    }
});
router.get('/setting', auth, async function (req, res, next) {
    res.render('setting.html');
});
router.post('/change_pwd', auth, async function (req, res, next) {
    try {
        const old_password = req.body.old_password // 获取旧密码
        const new_password = req.body.new_password
        const new_password1 = req.body.new_password1
        if (new_password !== new_password1) {
            return res.json({
                err_code: -1,
                msg: '两次输入的密码不一致'
            })
        }
        const user_id = req.session.user.user_id
        const user = await User.findOne({"_id": user_id}).select('password')
        if (user) {
            if (user.password !== encryptionData(old_password)) {
                return res.json({
                    err_code: -3,
                    msg: '旧密码错误'
                })
            } else {
                try {
                    const u = await User.updateOne({"_id": user_id}, {password: encryptionData(new_password)})
                    if (u.ok === 1) {
                        req.session.destroy(); // 销毁session
                        res.redirect('/user/login');
                    } else {
                        return res.json({
                            err_code: -1,
                            msg: '密码修改失败'
                        })
                    }
                } catch (e) {
                    return res.json({
                        err_code: -200,
                        msg: '服务器错误'
                    })
                }
            }
        } else {
            return res.status(404).json({
                err_code: -2,
                msg: '用户不存在'
            })
        }
    } catch (e) {
        console.log(e)
        return res.json({
            err_code: -1,
            msg: '服务器错误'
        })
    }
})
// 用户中心的博客
router.get('/blog', auth, async function(req, res) {
    const user_session = req.session.user;
    if (user_session) {
        res.render('blog_manage.html')
    } else {
        res.redirect('/user/login');
    }
})

// 用户管理的编辑
router.get('/blog/edit', auth, async function(req, res) {
    const id = req.query.id; // 文章id 有id则是编辑模式
    if (id) {
        const blog = await Blog.findOne({_id: id}).lean()
        res.render('blog_edit.html', {blog})
    } else {
        res.render('blog_edit.html')
    }
})

// 删除文章
router.get('/blog/delete', auth, async (req, res, next) => {
    const id = req.query.id
    try {
        const blog = await Blog.deleteOne({_id: id})
        if (blog) {
            return res.json({
                err_code: 0,
                msg: '删除成功'
            })
        } else {
            return res.json({
                err_code: -1,
                msg: '删除失败'
            })
        }
    } catch (e) {
        return res.json({
            err_code: -1,
            msg: '服务器错误'
        })
    }
})

module.exports = {
    router,
    auth
}
